package com.xb.loan.admin.web.controller.system;

import com.xb.loan.admin.Constants;
import com.xb.loan.admin.bean.system.OssOperator;
import com.xb.loan.admin.bean.system.OssOperatorRole;
import com.xb.loan.admin.bean.system.OssRole;
import com.xb.loan.admin.service.dict.DictEnumService;
import com.xb.loan.admin.service.operatormanager.OperatorManagerService;
import com.xb.loan.admin.service.system.OperatorRoleService;
import com.xb.loan.admin.service.system.OssRoleService;
import com.xb.loan.admin.web.controller.BaseController;
import com.xb.loan.log.exception.BizException;
import com.xb.loan.util.PasswordHelper;
import com.xb.loan.util.log.LogFormatTemplate4CenterOSS;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class OperatorManagementController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(OperatorManagementController.class);
	
	@Autowired
	private OperatorManagerService operatorManagerService;
	
	@Autowired
	private OssRoleService ossRoleService;
	
	@Autowired
	private DictEnumService dictEnumService;

	
	/*渠道登录密码重置值，默认为888888*/
    @Value("${userinfo.loginPassword.resetValue}")    
    private String loginPasswordResetValue; 
    
    @Autowired
	private OperatorRoleService operatorRoleService;
	
	@RequiresPermissions("103010100")
	@RequestMapping(value="/operatorManagement/showSaveOrUpdateOperator",method=RequestMethod.GET)
	public String showSaveOrUpdateOperator(Model model,HttpServletRequest req,
			@RequestParam(value="type",required=true)String type,
			@RequestParam(value="operatorId",required=false)String operatorId){
		try {
			if ("update".equals(type)) {
				Map<String, Object> map = operatorManagerService.queryOssOperatorById(operatorId);
				model.addAttribute("ossOperator", map);
			}
			String loginOperatorId = super.getOperatorId(req);
			String loginRoleId="";
		    List<OssOperatorRole> rolelist = operatorRoleService.queryOperatorRoleByOperatorId(loginOperatorId);

		    if(rolelist != null && rolelist.size() > 0){
		     	loginRoleId = rolelist.get(0).getRoleId();
		    }
			
			List<OssRole> ossRoleList = ossRoleService.queryOssRoleList(loginRoleId);

			//List<TAicheRepairDTO> repairList = repairService.queryRepariAll();

		    /*
			//部门信息
			List<DictEnum> departmentList = dictEnumService.queryDictEnumByType("DEPARTMENT_TYPE");
			//职称信息
			List<DictEnum> positionList = dictEnumService.queryDictEnumByType("POSITION_TYPE");
			model.addAttribute("departmentList", departmentList);
			model.addAttribute("positionList", positionList);
		    model.addAttribute("repairList",repairList);*/
			model.addAttribute("sutype", type);
			model.addAttribute("ossRoleList", ossRoleList);
			this.getLoginUserType(req, model);
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		this.getLoginUserType(req, model);
		return "/systemManagement/operatorManagement/saveOrUpdateOperator/saveOrUpdateOperator";
	}
	
	
	@ResponseBody
	@RequestMapping(value="/operatorManagement/saveOrUpdateOperator",method=RequestMethod.POST )
	public Map<String, Object> saveOrUpdateOperator(HttpServletRequest req,
			@RequestParam(value="sutype",required=true)String sutype,
			@RequestParam(value="roleId",required=false)String roleId,OssOperator oo){
		logger.info("OperatorManagementController.saveOrUpdateOperator type="+sutype+",roleId="+roleId+
				",loginName="+oo.getLoginName()+",name="+oo.getName()+",logPwd="+oo.getLoginPwd()+
				",company="+oo.getCompany()+",department="+oo.getDepartment()+",position="+oo.getPosition()+",phone="+oo.getPhone());
		Map<String, Object> map = new HashMap<String, Object>();
		String msg = OPERATE_RESULT_SUCCESS_MSG;
		String errorCode = OPERATE_RESULT_SUCCESS_CODE;
		if (sutype.equals("save")) {
			String loginPwd = PasswordHelper.encryptPassword(oo.getLoginPwd(), oo.getLoginName());
			oo.setLoginPwd(loginPwd);
			logger.info("OperatorManagementController.saveOrUpdateOperator 加密后密码:"+loginPwd);
		}
		try {
			operatorManagerService.saveOrUpdateOperator(sutype, roleId, oo);
			addOperateLog(req, "t_oss_operator", ("save".equals(sutype)==true?"添加":"修改")+"了操作员 roleId="+roleId+",operatorId="+oo.getOperatorId()+",loginName="+oo.getLoginName(), oo.getOperatorId(), "save".equals(sutype)==true? Constants.OPERATE_TYPE_ADD:Constants.OPERATE_TYPE_MODIFY);
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof BizException) {
				msg = ((BizException)e).getMessage();
				errorCode = ((BizException)e).getKey();
			}else {
				msg = OPERATE_RESULT_EXCEPTION_MSG;
				errorCode = OPERATE_RESULT_EXCEPTION_CODE;
			}
			logger.error(msg,e);
		} finally {
			map.put("msg", msg);
			map.put("errorCode", errorCode);
		}
		return map;
	}
	/**
	 * 跳转到管理员分页查询页面
	 * 2015年12月16日 09:38:33 lxh
	 */
	@RequiresPermissions("103020200")
	@RequestMapping(value="/operatorManagement/showOperatorList",method=RequestMethod.GET )
	public String showOperatorList(Model model,HttpServletRequest req){
		logger.info("OperatorManagementController.showOperatorList");
		this.getLoginUserType(req, model);
		return "/systemManagement/operatorManagement/operatorManager/showOperator";
		
	}
	/**
	 * 分页操作员列表
	 * @param pageNum
	 * @param numPerPage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/operatorManagement/queryOperatorList",method=RequestMethod.POST )
	public Map<String, Object> queryOperatorList(
			@RequestParam(value = "pageNum", required = false) int pageNum, 
			@RequestParam(value = "numPerPage", required = false) int numPerPage,HttpServletRequest req){
		logger.info("OperatorManagementController.queryOperatorList pageNum="+pageNum+",numPerPage="+numPerPage);
		Map<String, Object> map = new HashMap<String, Object>();

		
		String operatorId = super.getOperatorId(req);
		String loginRoleId="";
	    List<OssOperatorRole> rolelist = operatorRoleService.queryOperatorRoleByOperatorId(operatorId);
	    if(rolelist != null && rolelist.size() > 0){
	     	loginRoleId = rolelist.get(0).getRoleId();
	    }
        
		List<OssOperator> ossOperatorlist = operatorManagerService.queryOperatorList(numPerPage, pageNum,loginRoleId);
		int totalCount = operatorManagerService.queryOperatorCount(loginRoleId);
		map.put("json", ossOperatorlist);
		map.put("totalCount", totalCount);
		map.put("pageNum", pageNum);
		map.put("numPerPage", numPerPage);
		return map;
	}
	/**
	 * 删除操作员
	 * @param operatorId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/operatorManagement/deleteOperator",method=RequestMethod.POST )
	public Map<String, Object> deleteOperator(String operatorId,HttpServletRequest req){
		logger.info("OperatorManagementController.deleteOperator operatorId="+operatorId);
		String loginOperatorId = this.getOperatorId(req);
		
		Map<String, Object> map = new HashMap<String, Object>();
		String msg = "操作成功";
		int errorCode = 0;
		if(!loginOperatorId.equals(operatorId)){
			try {
				operatorManagerService.deleteOperator(operatorId);
			} catch (Exception e) {
				msg = e.getMessage();
				errorCode = 1;
				logger.error(msg,e);
			}
		}else{
			msg = "登录用户不能删除";
			errorCode = 1;
		}
		map.put("msg", msg);
		map.put("errorCode", errorCode);
		return map;
	}
	//重置密码
    @ResponseBody
    @RequestMapping("/operatorManagement/resetPwd")
    public Map<String, Object> resetPwd(String operatorId,String loginName) throws Exception { 
        String newPassword=PasswordHelper.encryptPassword(loginPasswordResetValue,loginName);
        
        int errorCode = -1;
        String msg =null;
        String logResult=null;
        try {
            int effectRow=operatorManagerService.updateLoginPassWord(operatorId,newPassword);
            if (effectRow==1) {
                errorCode = 0;
                msg = "操作成功,新密码为："+loginPasswordResetValue;
                logResult="success";
            }else {
                errorCode = 2;
                msg = "操作失败";
                logResult="failure";
            }
        } catch (BizException e) {
            logger.error(e.getMessage(),e);
            logResult="exception";
            msg = "系统异常";
        }
        
        logger.info(LogFormatTemplate4CenterOSS.
                PAM_RESET_LOGINPASSWORD,
                new String[]{"partnerAccountManagement",operatorId,logResult});
        
        Map<String, Object> resultMap = new HashMap<String, Object>();    
        resultMap.put("msg", msg);
        resultMap.put("errorCode", errorCode);
        return resultMap;

    }
    
    
  //重置密码
    @ResponseBody
    @RequestMapping("/operatorManagement/updateLoginPwd")
    public Map<String, Object> updateLoginPwd(HttpServletRequest req,String oldPwd,String newPwd) throws Exception { 
    	HttpSession session = req.getSession();
    	String operatorId = (String)session.getAttribute(Constants.SESSION_OPERATOR_ID);
    	String loginName = (String)session.getAttribute(Constants.SESSION_LOGIN_NAME);
    	
        String newPassword=PasswordHelper.encryptPassword(newPwd,loginName);
        OssOperator ossOperator = operatorManagerService.getOssOperatorById(operatorId);
        String oldpassword= PasswordHelper.encryptPassword(oldPwd,loginName);
        Map<String, Object> resultMap = new HashMap<String, Object>();    
        if(!oldpassword.equals(ossOperator.getLoginPwd())){
        	resultMap.put("msg", "原始密码错误");
            resultMap.put("errorCode", 1);
            logger.info(LogFormatTemplate4CenterOSS.
                    PAM_RESET_LOGINPASSWORD,
                    new String[]{"partnerAccountManagement",operatorId,"old pwd error"});    
            return resultMap;
        }
        
        
        int errorCode = -1;
        String msg =null;
        String logResult=null;
        try {
            int effectRow=operatorManagerService.updateLoginPassWord(operatorId,newPassword);
            if (effectRow==1) {
                errorCode = 0;
                msg = "操作成功";
                logResult="success";
            }else {
                errorCode = 2;
                msg = "操作失败";
                logResult="failure";
            }
        } catch (BizException e) {
            logger.error(e.getMessage(),e);
            logResult="exception";
            msg = "系统异常";
        }
        
        logger.info(LogFormatTemplate4CenterOSS.
                PAM_RESET_LOGINPASSWORD,
                new String[]{"partnerAccountManagement",operatorId,logResult});        
        
        resultMap.put("msg", msg);
        resultMap.put("errorCode", errorCode);
        return resultMap;

    }
	
}
